//
//  WOHomeViewController.m
//  WOPrototype
//
//  Created by Olof Millberg on 2010-04-26.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import <AddressBook/AddressBook.h>
#import "WOPrototypeAppDelegate.h"
#import "WOHomeViewController.h"
#import "WOListViewController.h"
#import "WOSettingsViewController.h"

@implementation WOHomeViewController

@synthesize locationManager;

#pragma mark Initialization Methods

/* Associates the class itself with the correct nib file */
- (id) init
{
	if (self = [super initWithNibName:@"HomeView" bundle:[NSBundle mainBundle]])
	{
		self.title = @"Hem";
	}
	return self;
}

/* The view is created for the first time */
- (void) viewDidLoad
{
	[super viewDidLoad];
	
	UILabel *titleView = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 30.0f)] autorelease];
	[titleView setBackgroundColor:[UIColor clearColor]];
	[titleView setTextColor:[UIColor whiteColor]];
	[titleView setTextAlignment:UITextAlignmentCenter];
	WOPrototypeAppDelegate *appDelegate = (WOPrototypeAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSString *titleText = [NSString stringWithFormat:@"Trawoh - %@",appDelegate.currentUser.lastName];
	[titleView setText:titleText];
	[titleView setFont:[UIFont boldSystemFontOfSize:15]];
	self.navigationItem.titleView = titleView;
	
	self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
}

/* The view appears */
- (void) viewDidAppear:(BOOL)animated
{
	//Force user selection.
	WOPrototypeAppDelegate *appDelegate = (WOPrototypeAppDelegate *)[[UIApplication sharedApplication] delegate];
	if(appDelegate.currentUser == nil)
		[self forceUserSelection];
}

/* Deallocate stuff */
- (void) dealloc
{
	if (locationManager)
		[locationManager release];
	[super dealloc];
}

#pragma mark -

#pragma mark Other Methods

/* The view for listing all work orders is psuhed */
- (IBAction)viewWorkOrders:(id)sender
{
	WOListViewController *woListVC = [[WOListViewController alloc] init];
	[self.navigationController pushViewController:woListVC animated:YES];
	[woListVC release];
}

/* The view for selecting address book contacts is pushed */
- (IBAction)viewAddressBook:(id)sender
{
	ABPeoplePickerNavigationController *peoplePickerNavigationController
	= [[ABPeoplePickerNavigationController alloc] init];
	
	peoplePickerNavigationController.peoplePickerDelegate = self;
	peoplePickerNavigationController.displayedProperties = [NSArray arrayWithObjects:
															[NSNumber numberWithInt:kABPersonPhoneProperty],
															[NSNumber numberWithInt:kABPersonEmailProperty], nil];
	
	[self presentModalViewController:peoplePickerNavigationController animated:YES];
	[self navigationController:peoplePickerNavigationController didShowViewController:peoplePickerNavigationController animated:YES];
}

- (void) navigationController:(UINavigationController *)navigationController 
		didShowViewController:(UIViewController *)viewController 
					 animated:(BOOL)animated 
{ 
	if([navigationController.viewControllers count] > 1) 
	{	navigationController.delegate = nil; 
		[navigationController popViewControllerAnimated:NO];
	} 
}

/* The view for settings is pushed */
- (IBAction)viewSettings:(id)sender
{
	WOSettingsViewController *woSettingsVC = [[WOSettingsViewController alloc] init];
	[self.navigationController pushViewController:woSettingsVC animated:YES];
	[woSettingsVC release];
}

/* Google Maps is launched */
- (IBAction)viewGoogleMaps:(id)sender
{
	CLLocation *currentLocation = [locationManager location];
	
	//Starting address - current position.
	CLLocationCoordinate2D currentCoordinate = [currentLocation coordinate];
	float startingLatitude = currentCoordinate.latitude;
	float startingLongitude = currentCoordinate.longitude;
	
	//Create the url.
	NSString* url = [NSString stringWithFormat: @"http://maps.google.com/maps?q=%f,%f&z=16",
					 startingLatitude, 
					 startingLongitude];
	
	//(Magical) launch of Google Maps.
	[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];	
}

/* The UIActionSheet with selectable users is displayed */
- (void) forceUserSelection
{
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Välj användare"
													  delegate:self
											 cancelButtonTitle:nil
										destructiveButtonTitle:nil
											 otherButtonTitles:nil];
	
	WOPrototypeAppDelegate *appDelegate = (WOPrototypeAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	for (WOPerson *user in appDelegate.users)
	{
		[actionSheet addButtonWithTitle:[NSString stringWithFormat:@"%@ %@", user.firstName, user.lastName]];
	}
	[actionSheet showInView: self.view.window];
}

#pragma mark -

#pragma mark CLLocationManagerDelegate Methods

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
	CLLocation *currentLocation = [locationManager location];
	
	//Starting address - current position.
	CLLocationCoordinate2D currentCoordinate = [currentLocation coordinate];
	float startingLatitude = currentCoordinate.latitude;
	float startingLongitude = currentCoordinate.longitude;
	
	//Create the url.
	NSString* url = [NSString stringWithFormat: @"http://maps.google.com/maps?q=%f,%f&z=16",
					 startingLatitude, 
					 startingLongitude];
	
	//(Magical) launch of Google Maps.
	[[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];		
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
	if ([error code] == kCLErrorDenied) {
		[locationManager stopUpdatingLocation];
		[locationManager release];
		locationManager = nil;
	}
}

#pragma mark -

#pragma mark UIActionSheet Delegate Methods

/* A button in the UIActionSheet is tapped */
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{	
	WOPrototypeAppDelegate *appDelegate = (WOPrototypeAppDelegate *)[[UIApplication sharedApplication] delegate];
			
	if (buttonIndex != actionSheet.cancelButtonIndex)
	{
		appDelegate.currentUser = [appDelegate.users objectAtIndex:buttonIndex];
	}
	[actionSheet release];
}

#pragma mark -

#pragma mark Addressbook Delegate Methods

/* The cancel button is tapped */
- (void) peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
	[self dismissModalViewControllerAnimated:YES];
	[peoplePicker release];
}

/* What happens when a contact entry is tapped */
- (BOOL) peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker
	   shouldContinueAfterSelectingPerson: (ABRecordRef) person
{
	return YES;
}

/* What happens when a property of a contact entry is tapped */
- (BOOL) peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker 
	   shouldContinueAfterSelectingPerson:(ABRecordRef)person 
								 property:(ABPropertyID)property 
							   identifier:(ABMultiValueIdentifier)identifier
{
	//Phone number tapped.
	if(property == kABPersonPhoneProperty)
	{
		//Get number and set up call launch.
		ABMultiValueRef phoneProperty = ABRecordCopyValue(person,property);
		NSString *phone = (NSString *)ABMultiValueCopyValueAtIndex(phoneProperty,identifier);
		NSString *phoneReadyToCall = [NSString stringWithFormat:@"tel://%@", phone];
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneReadyToCall]];
		
		//Release stuff.
		[phone release];
		if(phoneProperty != NULL)
			CFRelease(phoneProperty);
		
		[self dismissModalViewControllerAnimated:YES];
	}
	//Email address tapped.
	else if(property == kABPersonEmailProperty)
	{
		//Get address and set up mail lunch.
		ABMultiValueRef emailProperty = ABRecordCopyValue(person,property);
		NSString *email = (NSString *)ABMultiValueCopyValueAtIndex(emailProperty,identifier);
		NSString *emailReadyToSend = [NSString stringWithFormat:@"mailto://%@", email];
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:emailReadyToSend]];
		
		//Release stuff.
		[email release];
		if(emailProperty != NULL)
			CFRelease(emailProperty);
		[self dismissModalViewControllerAnimated:YES];
	}
	return YES;
}

#pragma mark -


@end